package net.daum.mail.util;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.InternetAddress;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;


public class MimeStringUtils {

	public static String cleanHtml(String text) {
		String cleanHtmlText = text;
		try {
			cleanHtmlText = Jsoup.clean(text, new Whitelist());
		} catch (Exception e) {
			// do not care
		}
		return cleanHtmlText;
	}

	public static String plainToHtml(String content) {
		if (StringUtils.isEmpty(content)) {
			return content;
		}
		return StringEscapeUtils.escapeHtml(content).replaceAll("(\r\n|\n)", "<br>");
	}

	
	public static String getStringFromInputStream(InputStream input) {
		String content = null;
		try {
			StringWriter writer = new StringWriter();
			IOUtils.copy(input, writer, "UTF-8");
			content = writer.toString();
		} catch(Exception e) {
			// ignore
		}
		return content;
	}
	
	/**
	 * InternetAddress 리스트를 UnicodeString으로 변환한다.
	 * @param InternetAddress[]
	 * @return "테스트" <test@test.com>, ... , "테스트2" <test2@test.com> 같은 형태의 String
	 */
	public static String addressesToUnicodeString(InternetAddress[] addresses) {
		List<String> list = new ArrayList<String>();
		for(InternetAddress address:addresses) {
			list.add(address.toUnicodeString());
		}
		return StringUtils.join(list.toArray(), ",");
	}
	
	
}
